<?php

namespace App\Util;

// 替换原生fputcsv操作
class CSVWriter
{
    private $handle;
    private $buffer = '';
    private $useBuffer = true; // 新增缓冲区控制开关

    public function __construct($filename, $useBuffer = true)
    {
        $this->handle = fopen($filename, 'wb');
        if (!$this->handle) {
            throw new \Exception("Failed to open file: $filename");
        }
        fwrite($this->handle, chr(0xEF) . chr(0xBB) . chr(0xBF));
        $this->useBuffer = $useBuffer;
    }

    public function writeRow(array $row)
    {
        $line = implode(',', array_map(function ($item) {
                return '"' . str_replace([
                        '"',
                        "\r",
                        "\n"
                    ], [
                        '""',
                        '\r',
                        '\n'
                    ], $item) . '"';
            }, $row)) . "\n";
        if ($this->useBuffer) {
            $this->buffer .= $line;
            if (strlen($this->buffer) > 1024 * 1024) { // 1MB缓冲区
                $this->flushBuffer();
            }
        } else {
            $this->directWrite($line);
        }
    }

    private function directWrite($line)
    {
        $re = fwrite($this->handle, $line);
        dump($re);
        fflush($this->handle);
    }

    private function flushBuffer()
    {
        if ($this->buffer !== '') {
            fwrite($this->handle, $this->buffer);
            fflush($this->handle);
            $this->buffer = '';
        }
    }

    public function close()
    {
        $this->flushBuffer();
        fclose($this->handle);
    }

    public function __destruct()
    {
        $this->close();
    }
}

// 使用示例


